package com.train.user.controller;

import com.train.common.annotation.Anonymous;
import com.train.common.core.controller.BaseController;
import com.train.common.core.domain.AjaxResult;
import com.train.common.core.domain.model.LoginUser;
import com.train.common.core.page.TableDataInfo;
import com.train.common.service.MinioService;
import com.train.common.utils.file.MinioUtils;
import com.train.common.utils.SecurityUtils;
import com.train.user.domain.Post;
import com.train.user.domain.PostCourse;
import com.train.user.domain.SysTopic;
import com.train.user.dto.PostCreateDTO;
import com.train.user.service.PostCourseService;
import com.train.user.service.PostService;
import com.train.user.service.SysPostCollectService;
import com.train.user.service.SysTopicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户动态管理 控制器
 *
 * @author train
 */
@RestController
@RequestMapping("/user/post")
public class PostController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PostController.class);

    @Autowired
    private PostService postService;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioService minioService;

    @Autowired
    PostCourseService postCourseService;

    @Autowired
    private SysPostCollectService sysPostCollectService;
    @Autowired
    private SysTopicService sysTopicService;

    /**
     * 发布动态
     */
    @PostMapping
    public AjaxResult createPost(@RequestBody Post post) {
        try {
            // 验证参数
//            if (post.getUserId() == null) {
//                return AjaxResult.error("用户ID不能为空");
//            }
            if (post.getContent() == null || post.getContent().trim().isEmpty()) {
                return AjaxResult.error("动态内容不能为空");
            }

            post.setUserId(getUserId());
            // 设置创建者信息
            post.setCreateBy(getUsername());
            post.setUpdateBy(getUsername());

            // 发布动态
            Post createdPost = postService.createPost(post);
            return AjaxResult.success("发布成功", createdPost);
        } catch (Exception e) {
            return AjaxResult.error("发布失败: " + e.getMessage());
        }
    }

    /**
     * 发布动态(带话题)
     */
    @PostMapping("/with-topics")
    public AjaxResult createPostWithTopics(@Validated @RequestBody PostCreateDTO dto) {
        try {
            // 创建Post对象
            Post post = new Post();
            post.setContent(dto.getContent());
            post.setImageUrls(dto.getImageUrls());
            post.setStatus(dto.getStatus() != null ? dto.getStatus() : "0");
            post.setUserId(getUserId());
            post.setCreateBy(getUsername());
            post.setUpdateBy(getUsername());
            Post createdPost = null;

            if (!dto.getTopicIds().isEmpty()) {
                // 发布动态(带话题验证)
                createdPost = postService.createPostWithTopics(post, dto.getTopicIds(),dto.getTopics());
            }
            return AjaxResult.success("发布成功", createdPost);
        } catch (Exception e) {
            return AjaxResult.error("发布失败: " + e.getMessage());
        }
    }

    @PostMapping("/course")
    public AjaxResult createPostCourse(@RequestBody Post post) {
        try {
            // 验证参数
//            if (post.getUserId() == null) {
//                return AjaxResult.error("用户ID不能为空");
//            }
            if (post.getContent() == null || post.getContent().trim().isEmpty()) {
                return AjaxResult.error("动态内容不能为空");
            }

            post.setUserId(getUserId());
            // 设置创建者信息
            post.setCreateBy(getUsername());
            post.setUpdateBy(getUsername());

            // 发布动态
            Post createdPost = postService.createPost(post);

            PostCourse postCourse = new PostCourse();
            postCourse.setPostId(createdPost.getPostId());
            postCourse.setCreateBy(SecurityUtils.getUsername());

            postCourseService.save(postCourse);

            SysTopic sysTopic = new SysTopic();
            sysTopic.setTopicName("课程动态");
            sysTopic.setCreateBy(SecurityUtils.getUsername());
            sysTopic.setUpdateBy(SecurityUtils.getUsername());
            sysTopicService.save(sysTopic);
            return AjaxResult.success("发布成功", createdPost);
        } catch (Exception e) {
            return AjaxResult.error("发布失败: " + e.getMessage());
        }
    }

    @GetMapping("/post/course")
    public AjaxResult getPostCourses(@RequestParam(required = false) LocalDateTime createTime, @RequestParam(required = false) Long relationId){
        List<PostCourse> postCourses = postCourseService.selectPostCourse(createTime, relationId);
        return AjaxResult.success(postCourses);
    }

    /**
     * 编辑动态
     */
    @PutMapping("/{postId}")
    public AjaxResult updatePost(@PathVariable Long postId, @RequestBody Post post) {
        try {
            // 设置动态ID
            post.setPostId(postId);
            // 设置更新者信息
            post.setUpdateBy(getUsername());

            // 编辑动态
            Post updatedPost = postService.updatePost(post);
            return AjaxResult.success("编辑成功", updatedPost);
        } catch (Exception e) {
            return AjaxResult.error("编辑失败: " + e.getMessage());
        }
    }

    /**
     * 删除动态
     */
    @DeleteMapping("/{postId}")
    public AjaxResult deletePost(@PathVariable Long postId) {
        try {
            // 获取当前用户ID（这里假设从token或session中获取）
            Long currentUserId = getCurrentUserId();

            // 删除动态
            boolean result = postService.deletePost(postId, currentUserId);
            if (result) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取动态详情
     */
    @GetMapping("/{postId}")
    public AjaxResult getPostDetail(@PathVariable Long postId) {
        try {
            // 获取动态详情
            Post post = postService.getPostById(postId);

            // 同时增加浏览数
            postService.incrementViewCount(postId);

            // 更新返回对象中的浏览数
            post.setViewCount(post.getViewCount() + 1);

            return AjaxResult.success("查询成功", post);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户动态列表
     */
    @GetMapping("/user/{userId}")
    public TableDataInfo getUserPosts(@PathVariable Long userId,
                                      @RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestParam(required = false) String orderBy) {
        try {
            // 设置分页参数
            Page<Post> page = new Page<>(pageNum, pageSize);
            // 分页查询
            IPage<Post> result = postService.getUserPosts(page, userId, orderBy);
            // 使用正确的getDataTable方法签名
            return getDataTable(result.getRecords());
        } catch (Exception e) {
            logger.error("查询用户动态列表失败", e);
            // 返回空的TableDataInfo以保持类型兼容
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setCode(500);
            tableDataInfo.setMsg("查询失败: " + e.getMessage());
            return tableDataInfo;
        }
    }

    /**
     * 获取动态列表 (滑动查询方式)
     */
    @GetMapping("/list")
    public AjaxResult getPosts(@RequestParam(required = false)
                                   @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
                                   LocalDateTime createTime,
                               @RequestParam(required = false) Long postId) {
        try {
            // 滑动查询
            List<Post> posts = postService.selectPosts(createTime, postId);
            return AjaxResult.success(posts);
        } catch (Exception e) {
            logger.error("查询动态列表失败", e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据话题ID获取动态列表 (滑动查询方式)
     */
    @GetMapping("/topic/{topicId}")
    public AjaxResult getPostsByTopicId(@PathVariable Long topicId,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
                                        @RequestParam(required = false) LocalDateTime createTime,
                                        @RequestParam(required = false) Long postId) {
        try {
            // 滑动查询
            List<Post> posts = postService.selectPostsByTopicId(topicId, createTime, postId);
            return AjaxResult.success(posts);
        } catch (Exception e) {
            logger.error("根据话题ID查询动态列表失败", e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 增加浏览数
     */
    @PostMapping("/view/{postId}")
    public AjaxResult incrementViewCount(@PathVariable Long postId) {
        try {
            // 增加浏览数
            Long currentViewCount = postService.incrementViewCount(postId);
            Map<String, Object> result = new HashMap<>();
            result.put("currentViewCount", currentViewCount);
            return AjaxResult.success("操作成功", result);
        } catch (Exception e) {
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 收藏动态
     */
    @PostMapping("/collect/{postId}")
    public AjaxResult collectPost(@PathVariable Long postId) {
        try {
            // 获取当前用户ID
            Long userId = getUserId();
            
            // 收藏动态
            boolean result = sysPostCollectService.collectPost(userId, postId);
            if (result) {
                return AjaxResult.success("收藏成功");
            } else {
                return AjaxResult.error("收藏失败，可能已收藏");
            }
        } catch (Exception e) {
            return AjaxResult.error("收藏失败: " + e.getMessage());
        }
    }

    /**
     * 取消收藏动态
     */
    @DeleteMapping("/collect/{postId}")
    public AjaxResult uncollectPost(@PathVariable Long postId) {
        try {
            // 获取当前用户ID
            Long userId = getUserId();
            
            // 取消收藏动态
            boolean result = sysPostCollectService.uncollectPost(userId, postId);
            if (result) {
                return AjaxResult.success("取消收藏成功");
            } else {
                return AjaxResult.error("取消收藏失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否已收藏动态
     */
    @GetMapping("/collect/{postId}")
    public AjaxResult checkCollect(@PathVariable Long postId) {
        try {
            // 获取当前用户ID
            Long userId = getUserId();
            
            // 检查是否已收藏
            boolean isCollected = sysPostCollectService.isPostCollected(userId, postId);
            Map<String, Object> result = new HashMap<>();
            result.put("isCollected", isCollected);
            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 上传动态图片
     */
    //url:[
    //      "http://8.138.160.18:9000/trainvideo/post/images/60a12529-1e55-4637-9339-6fbf74db8bf9.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=create%2F20251105%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251105T095400Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=3ed4a0dbc3b844e4ffc03147b6a0bbe27bddcc0f9241d72d981fc3613d3cd4c2",
    //      "http://8.138.160.18:9000/trainvideo/post/images/4adbb6cb-d13a-4b92-a5bd-2a8c60683b41.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=create%2F20251105%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251105T095400Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=79c9bfa9cae0bab2f5d86c8b99550e3ff5de71d9171afc925dc5a2e5ecdbc002"
    //    ]
    @PostMapping("/upload-image")
    public AjaxResult uploadImage(@RequestParam List<MultipartFile> file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 检查文件大小
            Map<String, Object> result = null;
            ArrayList<String> urls = new ArrayList<>();
            for (int i = 0; i < file.size(); i++) {
                long maxSize = 10 * 1024 * 1024; // 10MB
                if (file.get(i).getSize() > maxSize) {
                    return AjaxResult.error("文件大小不能超过10MB");
                }

                // 设置上传路径前缀
                String pathPrefix = "post/images/";

                // 生成唯一文件名
                String originalFilename = file.get(i).getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + extension;
                String objectName = pathPrefix + fileName;

                // 上传文件
                String uploadedObjectName = minioUtils.upload(file.get(i), objectName);

                // 直接使用objectname（将由AOP自动转换为临时URL）
                urls.add(uploadedObjectName);
            }
            result = new HashMap<>();
            result.put("objectNames", urls);

            return AjaxResult.success("图片上传成功", result);
        } catch (Exception e) {
            return AjaxResult.error("图片上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     * 从SecurityUtils中获取登录用户信息
     */
    private Long getCurrentUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                return loginUser.getUserId();
            }
            return null;
        } catch (Exception e) {
            logger.warn("获取当前用户ID失败: {}", e.getMessage());
            return null;
        }
    }
}